import 'dart:async';

import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:get/get.dart';

var filterName = '';

class HomeController extends GetxController {
  StreamSubscription<BLEPeripheral>? _scanSubscription;
  late Rx<BLEPeripheral> device;
  RxString id = ''.obs;
  RxString mac = ''.obs;
  RxString company_key = ''.obs;
  RxString company_value = ''.obs;
  RxString detail = ''.obs;
  RxString msd = ''.obs;
  RxString pressure = '0'.obs;
  RxString temp2 = ''.obs;
  RxString electricity = ''.obs;
  RxString rssi = ''.obs;

  @override
  void onInit() {
    super.onInit();
    _scanSubscription ??= BluetoothManager.instance.scanResultStream.listen((p0) {
      filter();
    });
  }

  @override
  void onClose() {
    _scanSubscription?.cancel();
  }

  void filter() {
    var de = BluetoothManager.instance.deviceList.firstWhereOrNull((p0) {
      return (p0.result.device.platformName.toUpperCase().contains(id.value.toUpperCase()) && id.value.isNotEmpty) ||
          mac.value.toUpperCase() == p0.mac.toUpperCase();
    });
    if (de != null) {
      device = de.obs;
      mac.value = de.mac;
      rssi.value = '${de.result.rssi}';
      company_key.value = de.result.advertisementData.manufacturerData.keys.toList().toHexstr();
      company_value.value = de.result.advertisementData.manufacturerData.values
          .map((e) => e.toHexstr())
          .toList()
          .join();
      var list = de.result.advertisementData.msd.last;
      msd.value = list.toHexstr();
      pressure.value = '${list.sublist(0, 2).decimal / 1000}';
      temp2.value = '${list.sublist(2, 4).decimal / 10}';
      electricity.value = '${list.last.toInt()}';
      print(
        '===================>rssi: ${rssi.value} \n company:${company_key} \n:company_value:${company_value}. \n msd:${msd.value}',
      );
    }
  }

  void updateIDorMac(idstring, macstring) {
    id.value = idstring as String;
    // mac.value = macstring as String;
    filter();
  }

  void refresh() {
    BluetoothManager.instance.startScan(deviceNameFilter: [filterName], duration: const Duration(seconds: 3));
  }
}
